// javaScript for jcvp_web
var ws;
var server_ip = window.location.host;
var g_chunks = [];
var g_chunks_id = 0;
var g_file;

function setupWebSocket()
{
	if ("WebSocket" in window) {
		ws = new WebSocket('ws://'+server_ip+'/ws/video');
		ws.onopen = function(event) {
			console.log('on opened!');
		};
		ws.onmessage = function(event) {
			if (typeof (event.data) === 'string') {
				json_data_parse(event.data);
			} else {
			}
		};
		ws.onclose = function(event) {
			console.log('on closed!');
		};
		ws.onerror = function(error) {
			console.error('on WebSocket error:', error);
		};
	} else {
		alert("unsupported WebSocket!");
	}
}
function json_data_parse(json_str)
{
	var json_obj = JSON.parse(json_str);
	if (json_obj.type === "run_state") {
		if (json_obj.show_mode === "clear") {
			document.getElementById('js_run_state').textContent = json_obj.state_str;
		} else if (json_obj.show_mode === "inline") {
			var lines = document.getElementById('js_run_state').textContent.split('\n');
			lines[lines.length-1] = json_obj.state_str;
			document.getElementById('js_run_state').textContent = lines;
		} else if (json_obj.show_mode === "newline") {
			document.getElementById('js_run_state').textContent = document.getElementById('js_run_state').textContent + '\n' + json_obj.state_str;
		};
	} else if (json_obj.type === "upload_resp") {
		if (json_obj.state === true) {
			g_chunks_id++;
			sendChunksToServer(g_chunks, g_file.name, g_file.size, g_chunks_id);
		};
	} else {
		console.log('未知type:', json_obj.type);
	}
}

function on_jc_deb_upload()
{
	document.getElementById('progress_val').style.width = 0 + "%";
	document.getElementById('progress_val').textContent = 0 + "%";
	document.getElementById('js_run_state').textContent = " ";

	var input = document.getElementById('jc_deb_file');
	g_file = input.files[0];
	if (!g_file) {
		return;
	}
	var reader = new FileReader();
	reader.onload = function(e) {
		g_chunks_id = 0;
		g_chunks = [];
		const bin_data = e.target.result;
		const chunkSize = 64*1024;
		const chunk_num = Math.ceil(bin_data.byteLength / chunkSize);
		for (let i = 0; i < chunk_num; i++) {
			const offset = i * chunkSize;
			const chunk = bin_data.slice(offset, offset + chunkSize);
			g_chunks.push(chunk);
		}
		sendChunksToServer(g_chunks, g_file.name, g_file.size, g_chunks_id);
	};
	reader.onerror = function(e) {
		console.error('File could not be read! Code: ' + e.target.error.code);
	};
	reader.readAsArrayBuffer(g_file);
}
function sendChunksToServer(chunks, file_name, file_size, index)
{
	if (index >= chunks.length) {
		return;
	};
	let op_passwd = document.getElementById("jc_op_passwd").value;
	if (ws.readyState === WebSocket.OPEN) {
		let raw_binary = '';
		const bytes = new Uint8Array(chunks[index]);
		for (let i = 0; i < bytes.byteLength; i++) {
			raw_binary += String.fromCharCode(bytes[i]);
		};
		var json_obj = {
			type: "upload",
			passwd: op_passwd,
			filename: file_name,
			all_chunk: chunks.length,
			cur_chunk: index+1,
			cur_size: chunks[index].byteLength,
			file_size: file_size,
			data: btoa(raw_binary),
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	};

	let cur_progress = ((index+1)*100/chunks.length).toFixed(2);
	document.getElementById('progress_val').style.width = cur_progress + "%";
	document.getElementById('progress_val').textContent = cur_progress + "%";
}

function on_page_load()
{
	setupWebSocket();
}
